<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Annuity extends MY_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->model(['annuity_user_model', 'annuity_record_model']);
	}
	
	public function release(){
		$userlist = $this->annuity_user_model->get_result([
			'status' => 1
		]);
		if(!$userlist){
			$this->output_json('没有找到符合条件的用户');
		}
		
		$month_start = strtotime(date('Y-m'));
		$month_end = strtotime(date('Y-m-t 23:59:59'));
		
		$type = 1;
		$userids = array_column($userlist, 'id');
		
		$records = $this->annuity_record_model->get_result([
			'where' => [
				'type' => $type,
				'inputtime >=' => $month_start,
				'inputtime <=' => $month_end
			],
			'where_in' => [
				'uid' => $userids
			]
		]);
		$records = array_column($records, 'uid');
		
		$data = [];
		$usr_data = [];
		$level_arr = $this->annuity_user_model->dict_options('level');
		$type_arr = $this->annuity_record_model->dict_options('type');
		
		foreach($userlist as $item){
			$uid = $item['id'];
			if(in_array($uid, $records)){
				continue;
			}
			$level = $item['level'];
			$bonus = $level_arr[$level]['bonus'];
			$new_total = $item['total'] + $bonus;
			if($bonus){
				$usr_data[] = [
					'id' => $uid,
					'total' => $new_total
				];
				$data[] = [
					'uid' => $uid,
					'level' => $level,
					'level_name' => $level_arr[$level]['label'],
					'type' => $type,
					'subject' => $type_arr[$type],
					'amount' => $bonus,
					'total' => $new_total,
					'inputtime' => time()
				];
			}
		}
		if(!$data){
			$this->output_json('已经发放过了');
		}
		$query = $this->annuity_record_model->batch_insert($data);
		if($query){
			$query = $this->annuity_user_model->batch_update($usr_data);
			if($query){
				$this->output_json('发放成功', 0);
			}
			$this->output_json('更新用户金额失败', 0);
		}
		$this->output_json('发放失败', 0);
	}
	
}